import java.io.*;
import java.util.Arrays;

/**
 * @Author Nino 2020/9/1
 */
public class ConvertGBK2Utf8 {
    public static void main(String[] args) {
        String src = "C:\\Users\\zhu.chunfeng\\Desktop\\文件夹\\project\\gitee\\demo-parent\\7stock\\src\\main\\resources\\hs300_gbk";
        String des = "C:\\Users\\zhu.chunfeng\\Desktop\\文件夹\\project\\gitee\\demo-parent\\7stock\\src\\main\\resources\\hs300_utf8";
        try {
            convertGBK2U8(src, des);
            System.out.println("200");
        } catch (IllegalArgumentException e) {
            System.out.println("要被转换的文件不存在！");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Convert fails!");
        }
    }

    private static void convertGBK2U8(String src, String des) throws Exception {
        File srcFile = new File(src);
        File desFile = new File(des);

        if (!srcFile.exists()) {
            throw new IllegalArgumentException();
        }
        if (!desFile.exists()) {
            desFile.mkdirs();
        }
        File[] srcLists;
        if (srcFile.isDirectory()) {
            srcLists = srcFile.listFiles();
        }else{
            srcLists = new File[1];
            srcLists[0] = srcFile;
        }
        for (File file : srcLists) {
            if (file.isDirectory()) {
                convertGBK2U8(file.getPath(), des + "\\" + file.getName());
            } else {
                InputStreamReader is = new InputStreamReader(new FileInputStream(file), "GBK");
                OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(des + "\\" + file.getName()), "UTF-8");
                char[] chars = new char[1];
                int len = -1;
                while ((len = is.read(chars)) != -1) {
                    os.write(chars, 0, chars.length);
                }
//                os.flush();
                os.close();
                is.close();
            }
        }
    }
}